var express = require('express');
var fs = require('fs');

var app = express();

var upload_ids = [];
var next_id = 0;
var file_names = [];

app.post('/upload', function (req, res) {
  	upload_ids[next_id] = true;
  	res.set("upload_id", (next_id++).toString());
    res.send();
});

app.put('/upload/:upload_id', function (req, res) {
    if (upload_ids[parseInt(req.params.upload_id)] == true) {
        var filename = req.params.upload_id+Date.now();
        if (parseInt(req.headers['offset']) == 0) file_names[req.params.upload_id] = filename;
        else filename = file_names[req.params.upload_id];
        var filepath = "./upload/"+filename;
        req.pipe(fs.createWriteStream(filepath, {'flags': 'a'}));
    }
    res.send();
});

app.get('/upload/:upload_id', function (req, res) {
    if (upload_ids[req.params.upload_id] == true) {
        if (req.headers['content-length'] != undefined) {
            fs.stat(file_names[req.params.upload_id], function(err, states) {
                res.set('offset', states.size.toString());
                res.send();
            });
        } else {
            fs.stat(file_names[req.params.upload_id], function(err, states) {
                res.set('origin_size', states.size.toString());
                res.set('origin_url', file_names[req.params.upload_id]);
                res.send();
            });
        }
    } else res.send();
});

app.get('/download/:filename', function (req, res) {
    var filepath = "./upload/"+req.params.filename;
    fs.exists(filepath, function(exist) {
        if (!exist) {
            res.send(req.params.filename+" is not found");
        } else {
            if (req.headers['range'] == undefined) {
                fs.createReadStream("./upload/"+req.params.filename).pipe(res);
            } else {
                var arg = req.headers['range'].split(",");
                fs.createReadStream(filepath, {start: parseInt(arg[0]), end: parseInt(arg[1])}).pipe(res);
            }
            //res.send();
        }
    });
});

var server = app.listen(8080, function () {
    console.log("listen at 8080");
});
